package net.asfun.jvalog.service;

import java.util.ArrayList;
import java.util.List;

import com.google.appengine.api.datastore.Key;

import net.asfun.jvalog.common.GMCacher;
import net.asfun.jvalog.common.JdoerFactory;
import net.asfun.jvalog.entity.File;
import net.asfun.jvalog.resource.FileDao;
import net.asfun.jvalog.util.Unifier;
import net.asfun.jvalog.vo.Media;
import net.asfun.jvalog.vo.Pager;

public class MediaService {

	public static List<Media> listAll(Pager pager) {
		List<Media> medias = new ArrayList<Media>();
		for ( File file : FileDao.listAll(pager) ) {
			medias.add(new Media(file));
		}
		return medias;
	}

	public static void delete(Long id) {
		File file = JdoerFactory.jdoFile.load(id);
		Unifier.unsetUnique(file.getKey(), "name");
		GMCacher.remove("/media/" + file.getName());//TODO 
		JdoerFactory.jdoFile.delete(file);
	}

	public static Media getById(Long id) {
		return new Media(JdoerFactory.jdoFile.load(id));
	}

	public static void rename(Long id, String name) {
		File file = JdoerFactory.jdoFile.load(id);
		file.setName(uniqueURI(file.getName(), file.getKey()));
		Unifier.setUnique(file.getKey(), "name", file.getName());
		GMCacher.remove("/media/" + file.getName());//TODO 
	}

	public static void add(File file) {
		file.setName(uniqueURI(file.getName()));
		JdoerFactory.jdoFile.save(file);
		Unifier.setUnique(file.getKey(), "name", file.getName());
	}

	public static Media getByName(String name) {
		return new Media(FileDao.getByName(name));
	}

	private static String uniqueURI(String name) {
		if ( ! Unifier.isUnique("File", "name", name)) {
			name += "~1";
			return name = uniqueURI(name);
		}
		return name;	
	}
	
	private static String uniqueURI(String name, Key key) {
		if ( ! Unifier.isUnique(key, "name", name)) {
			name += "~1";
			return name = uniqueURI(name);
		}
		return name;	
	}
}
